<template>
  <view class="post-detail-container">
    <!-- 帖子内容 -->
    <scroll-view scroll-y class="post-content-scroll">
      <view class="post-content-container" v-if="post">
        <view class="post-header">
          <view class="user-info">
            <image class="user-avatar" :src="post.avatar || '/static/images/default-avatar.png'"></image>
            <view class="user-detail">
              <text class="username">{{ post.username || '我' }}</text>
              <text class="post-time">{{ formatTime(post.createdAt) }}</text>
            </view>
          </view>
          <view class="post-actions-dropdown" @click="showActionSheet">
            <text class="iconfont icon-more"></text>
          </view>
        </view>
        
        <view class="post-content">
          <text class="post-title">{{ post.title }}</text>
          <text class="post-text">{{ post.content }}</text>
        </view>
        
        <view class="post-images" v-if="post.images && post.images.length">
          <image 
            v-for="(img, index) in post.images" 
            :key="index" 
            :src="img" 
            mode="widthFix" 
            class="post-image"
            @click="previewImage(index)"
          ></image>
        </view>
        
        <view class="post-meta" v-if="post.tags || post.location">
          <view class="post-tags" v-if="post.tags && post.tags.length">
            <text class="tag-item" v-for="tag in post.tags" :key="tag">{{ getTagName(tag) }}</text>
          </view>
          
          <view class="post-location" v-if="post.location">
            <text class="iconfont icon-location"></text>
            <text class="location-text">{{ post.location }}</text>
          </view>
        </view>
        
        <view class="post-stats">
          <view class="stat-item" @click="toggleLike">
            <text class="iconfont" :class="post.isLiked ? 'icon-like-filled' : 'icon-like'"></text>
            <text class="stat-count">{{ post.likes }}</text>
          </view>
          <view class="stat-item">
            <text class="iconfont icon-comment"></text>
            <text class="stat-count">{{ post.comments ? post.comments.length : 0 }}</text>
          </view>
          <view class="stat-item" @click="sharePost">
            <text class="iconfont icon-share"></text>
            <text class="stat-count">分享</text>
          </view>
        </view>
        
        <!-- 评论区 -->
        <view class="comments-section">
          <view class="section-header">
            <text class="section-title">评论 {{ post.comments ? post.comments.length : 0 }}</text>
          </view>
          
          <view class="empty-comments" v-if="!post.comments || post.comments.length === 0">
            <text class="empty-text">暂无评论，快来抢沙发吧！</text>
          </view>
          
          <view class="comments-list" v-else>
            <view class="comment-item" v-for="comment in post.comments" :key="comment.id">
              <image class="comment-avatar" :src="comment.avatar || '/static/images/default-avatar.png'"></image>
              <view class="comment-content">
                <view class="comment-header">
                  <text class="comment-username">{{ comment.userName }}</text>
                  <text class="comment-time">{{ formatTime(comment.createdAt) }}</text>
                </view>
                <text class="comment-text">{{ comment.text }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <view class="loading-container" v-else>
        <text class="loading-text">加载中...</text>
      </view>
    </scroll-view>
    
    <!-- 评论输入框 -->
    <view class="comment-input-container">
      <input 
        class="comment-input" 
        v-model="commentText" 
        placeholder="写评论..." 
        confirm-type="send"
        @confirm="submitComment"
      />
      <button class="send-btn" :disabled="!commentText.trim()" @click="submitComment">发送</button>
    </view>
  </view>
</template>

<script>
import { usePostStore } from '@/store/postStore';

export default {
  data() {
    return {
      postId: '',
      post: null,
      commentText: '',
      availableTags: [
        { name: '无障碍设施', value: 'accessibility' },
        { name: '活动', value: 'event' },
        { name: '建议', value: 'suggestion' },
        { name: '问题', value: 'problem' },
        { name: '分享', value: 'share' },
        { name: '其他', value: 'other' }
      ],
      tagMap: {},
      defaultImages: {
        avatars: {
          me: 'https://picsum.photos/id/1005/200/200',
          user1: 'https://picsum.photos/id/1012/200/200',
          user2: 'https://picsum.photos/id/1025/200/200',
          user3: 'https://picsum.photos/id/1074/200/200',
          user4: 'https://picsum.photos/id/1084/200/200',
          org1: 'https://picsum.photos/id/119/200/200',
        },
        samples: {
          elevator1: 'https://picsum.photos/id/164/800/600',
          elevator2: 'https://picsum.photos/id/180/800/600',
          event: 'https://picsum.photos/id/184/800/600',
          scenic1: 'https://picsum.photos/id/193/800/600',
          scenic2: 'https://picsum.photos/id/30/800/600',
        }
      }
    };
  },
  
  onLoad(options) {
    if (options.id) {
      this.postId = options.id;
      this.loadPostData();
    } else {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
    
    // 转换tags为map
    this.availableTags.forEach(tag => {
      this.tagMap[tag.value] = tag.name;
    });
  },
  
  methods: {
    loadPostData() {
      const postStore = usePostStore();
      this.post = postStore.getPostById(this.postId);
      
      if (!this.post) {
        uni.showToast({
          title: '帖子不存在',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } else {
        // 替换帖子中的图片URL为伪图片
        this.replaceImageUrls();
      }
    },
    
    replaceImageUrls() {
      if (!this.post) return;
      
      // 替换头像
      if (this.post.avatar && this.post.avatar.includes('/static/images/avatars/')) {
        const avatarName = this.post.avatar.split('/').pop().replace('.png', '');
        if (this.defaultImages.avatars[avatarName]) {
          this.post.avatar = this.defaultImages.avatars[avatarName];
        } else {
          this.post.avatar = this.defaultImages.avatars.user1;
        }
      }
      
      // 替换帖子图片
      if (this.post.images && this.post.images.length) {
        this.post.images = this.post.images.map(img => {
          if (img.includes('/static/images/sample/')) {
            const imageName = img.split('/').pop().replace('.jpg', '');
            if (this.defaultImages.samples[imageName]) {
              return this.defaultImages.samples[imageName];
            } else {
              // 随机返回一张图片
              const sampleKeys = Object.keys(this.defaultImages.samples);
              const randomKey = sampleKeys[Math.floor(Math.random() * sampleKeys.length)];
              return this.defaultImages.samples[randomKey];
            }
          }
          return img;
        });
      }
      
      // 替换评论头像
      if (this.post.comments && this.post.comments.length) {
        this.post.comments.forEach(comment => {
          if (!comment.avatar) {
            // 随机分配一个头像
            const avatarKeys = Object.keys(this.defaultImages.avatars);
            const randomKey = avatarKeys[Math.floor(Math.random() * avatarKeys.length)];
            comment.avatar = this.defaultImages.avatars[randomKey];
          }
        });
      }
    },
    
    toggleLike() {
      const postStore = usePostStore();
      postStore.toggleLike(this.postId);
      // 重新加载数据以更新UI
      this.loadPostData();
    },
    
    submitComment() {
      if (!this.commentText.trim()) return;
      
      const postStore = usePostStore();
      postStore.addComment(this.postId, this.commentText);
      
      // 清空评论输入
      this.commentText = '';
      
      // 重新加载数据以更新UI
      this.loadPostData();
      
      uni.showToast({
        title: '评论成功',
        icon: 'success'
      });
    },
    
    formatTime(timestamp) {
      if (!timestamp) return '';
      
      const date = new Date(timestamp);
      const now = new Date();
      const diff = now - date;
      
      // 小于1分钟
      if (diff < 60 * 1000) {
        return '刚刚';
      }
      
      // 小于1小时
      if (diff < 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 1000))}分钟前`;
      }
      
      // 小于24小时
      if (diff < 24 * 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
      }
      
      // 小于7天
      if (diff < 7 * 24 * 60 * 60 * 1000) {
        return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
      }
      
      // 大于7天
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    },
    
    getTagName(tagValue) {
      return this.tagMap[tagValue] || tagValue;
    },
    
    previewImage(index) {
      uni.previewImage({
        urls: this.post.images,
        current: index
      });
    },
    
    sharePost() {
      uni.showShareMenu({
        withShareTicket: true
      });
    },
    
    showActionSheet() {
      uni.showActionSheet({
        itemList: ['编辑', '删除', '举报'],
        success: (res) => {
          switch(res.tapIndex) {
            case 0: // 编辑
              this.editPost();
              break;
            case 1: // 删除
              this.deletePost();
              break;
            case 2: // 举报
              uni.showToast({
                title: '举报成功',
                icon: 'success'
              });
              break;
          }
        }
      });
    },
    
    editPost() {
      uni.navigateTo({
        url: `/pages/post/edit?id=${this.postId}`
      });
    },
    
    deletePost() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条帖子吗？删除后无法恢复。',
        success: (res) => {
          if (res.confirm) {
            const postStore = usePostStore();
            const success = postStore.deletePost(this.postId);
            
            if (success) {
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            }
          }
        }
      });
    }
  }
};
</script>

<style>
.post-detail-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f8fa;
}

.post-content-scroll {
  flex: 1;
  height: 0;
}

.post-content-container {
  background-color: #fff;
  padding: 30rpx;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.user-detail {
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.post-time {
  font-size: 24rpx;
  color: #999;
  margin-top: 6rpx;
}

.post-actions-dropdown {
  padding: 10rpx;
}

.post-content {
  margin-bottom: 30rpx;
}

.post-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.post-text {
  font-size: 30rpx;
  color: #333;
  line-height: 1.6;
  display: block;
}

.post-images {
  margin-bottom: 30rpx;
}

.post-image {
  width: 100%;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
}

.post-meta {
  margin-bottom: 30rpx;
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10rpx;
}

.tag-item {
  background-color: #f0f2f5;
  color: #666;
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  margin-right: 16rpx;
  margin-bottom: 16rpx;
}

.post-location {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #999;
}

.icon-location {
  margin-right: 8rpx;
}

.post-stats {
  display: flex;
  justify-content: space-around;
  padding: 20rpx 0;
  border-top: 1px solid #f0f2f5;
  border-bottom: 1px solid #f0f2f5;
  margin-bottom: 30rpx;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-item .iconfont {
  font-size: 36rpx;
  margin-right: 10rpx;
}

.icon-like-filled {
  color: #ff5151;
}

.stat-count {
  font-size: 28rpx;
  color: #666;
}

.comments-section {
  padding-bottom: 100rpx;
}

.section-header {
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
}

.empty-comments {
  padding: 60rpx 0;
  text-align: center;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}

.comments-list {
  
}

.comment-item {
  display: flex;
  margin-bottom: 30rpx;
  padding-bottom: 30rpx;
  border-bottom: 1px solid #f0f2f5;
}

.comment-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.comment-username {
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
}

.comment-time {
  font-size: 24rpx;
  color: #999;
}

.comment-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
}

.comment-input-container {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  border-top: 1px solid #f0f2f5;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

.comment-input {
  flex: 1;
  background-color: #f0f2f5;
  border-radius: 36rpx;
  padding: 16rpx 30rpx;
  font-size: 28rpx;
}

.send-btn {
  margin-left: 20rpx;
  background-color: #3F7BFC;
  color: #fff;
  border-radius: 36rpx;
  font-size: 28rpx;
  padding: 0 30rpx;
  height: 72rpx;
  line-height: 72rpx;
}

.send-btn[disabled] {
  background-color: #cccccc;
  color: #fff;
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 60rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}
</style> 